package com.banciyuan.wallpaper.page.setting;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.banciyuan.wallpaper.R;
import com.banciyuan.wallpaper.base.BaseActivity;
import com.banciyuan.wallpaper.page.DownLoadActivity;
import com.banciyuan.wallpaper.services.ListenSevices;
import com.banciyuan.wallpaper.setting.SettingConfig;
import com.banciyuan.wallpaper.util.CacheUtils;
import com.banciyuan.wallpaper.util.ScreenShots;
import com.banciyuan.wallpaper.util.UIUtils;
import com.bumptech.glide.Glide;

import java.io.File;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private View mContainerChangeWallpager;
    private ImageView mSwitchChangewallpager;
    private ImageView mSwitchWifichange;
    private View mContainerWifichange;
    private View mBoyTypeView;
    private View mGirlTypeView;
    private View mBoyTypeCheckView;
    private View mGirlTypeCheckView;
    private View mClearCacheView;
    private TextView mCacheSizeTv;
    private View mAboutBcyView;
    private ImageView mBackContainer;
    private CoordinatorLayout mSnack;
    private boolean mClearFlag = false;
    private String temp_sex;

    public final static int SETTING_CHANGE = 1003;
    public final static int SETTING_NOT_CHANGE = 1004;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        OnInitArgs();
        OnInitUI();
        OnInitAction();
    }

    @Override
    protected void OnInitArgs() {
        temp_sex = SettingConfig.ReadSettingString(getBaseContext(), SettingConfig.SEX);
    }

    @Override
    protected void OnInitUI() {
        mContainerChangeWallpager = findViewById(R.id.setting_changewallpager_container);
        mSwitchChangewallpager = (ImageView) findViewById(R.id.setting_changewallpager_switch);
        mContainerWifichange = findViewById(R.id.setting_wifichange_container);
        mSwitchWifichange = (ImageView) findViewById(R.id.setting_wifichange_switch);
        mBoyTypeView = findViewById(R.id.setting_boytype_view);
        mGirlTypeView = findViewById(R.id.setting_girltype_view);
        mBoyTypeCheckView = findViewById(R.id.setting_boytype_checkicon);
        mGirlTypeCheckView = findViewById(R.id.setting_girltype_checkicon);
        mClearCacheView = findViewById(R.id.setting_clearcache_view);
        mCacheSizeTv = (TextView) findViewById(R.id.setting_cache_size_tv);
        mAboutBcyView = findViewById(R.id.setting_about_bcy_view);
        mBackContainer = (ImageView) findViewById(R.id.back_container);
        mSnack = (CoordinatorLayout) findViewById(R.id.snack_container);
        mBackContainer.setImageBitmap(BitmapFactory.decodeFile(ScreenShots.IMAGE_TEMP_URI + ScreenShots.IMAGE_FILE_NAME));
        readStatus();
        renderCacheSize();
    }

    private void readStatus() {
        if (!SettingConfig.isSettingExit(getBaseContext(), SettingConfig.CHANGE)) {
            SettingConfig.WriteSettingBoolean(getBaseContext(), SettingConfig.CHANGE, true);
        }
        if (!SettingConfig.isSettingExit(getBaseContext(), SettingConfig.WIFI)) {
            SettingConfig.WriteSettingBoolean(getBaseContext(), SettingConfig.WIFI, true);
        }
        if (!SettingConfig.isSettingExit(getBaseContext(), SettingConfig.SEX)) {
            SettingConfig.WriteSettingString(getBaseContext(), SettingConfig.SEX, SettingConfig.BOY);
        }
        boolean change_flag = SettingConfig.ReadSettingBoolean(getBaseContext(), SettingConfig.CHANGE);
        boolean wifi_flag = SettingConfig.ReadSettingBoolean(getBaseContext(), SettingConfig.WIFI);
        String sex = SettingConfig.ReadSettingString(getBaseContext(), SettingConfig.SEX);

        mSwitchChangewallpager.setTag(change_flag);
        if (!change_flag) {
            setSwitchChangeOffView();
        }
        mSwitchWifichange.setImageResource(wifi_flag ? R.mipmap.ic_switch_on : R.mipmap.ic_switch_off);
        mSwitchWifichange.setTag(wifi_flag);
        if (sex.equals(SettingConfig.BOY)) {
            mBoyTypeCheckView.setVisibility(View.VISIBLE);
            mGirlTypeCheckView.setVisibility(View.INVISIBLE);
        } else {
            mBoyTypeCheckView.setVisibility(View.INVISIBLE);
            mGirlTypeCheckView.setVisibility(View.VISIBLE);
        }
    }

    private void setSwitchChangeOffView() {
        mSwitchChangewallpager.setImageResource(R.mipmap.ic_switch_off);
        mContainerChangeWallpager.setBackgroundResource(R.mipmap.ic_one_layer);
        ViewGroup.LayoutParams layoutParams = mContainerWifichange.getLayoutParams();
        layoutParams.height = 0;

        ViewGroup.LayoutParams changeWallPagerParams = mContainerChangeWallpager.getLayoutParams();
        changeWallPagerParams.height = UIUtils.dip2px(44, this);
        mContainerWifichange.setLayoutParams(layoutParams);
        mContainerChangeWallpager.setLayoutParams(changeWallPagerParams);
    }

    @Override
    protected void OnInitAction() {
        findViewById(R.id.setting_viewback).setOnClickListener(this);
        mSwitchChangewallpager.setOnClickListener(this);
        mSwitchWifichange.setOnClickListener(this);
        mBoyTypeView.setOnClickListener(this);
        mGirlTypeView.setOnClickListener(this);
        mClearCacheView.setOnClickListener(this);
        mAboutBcyView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_viewback:
                close();
                break;
            case R.id.setting_changewallpager_switch:
                if ((Boolean) mSwitchChangewallpager.getTag()) {
                    changeWallPagerSwitch(R.mipmap.ic_switch_off, R.mipmap.ic_one_layer, UIUtils.dip2px(44, this), 0);
                    stopService(new Intent(this, ListenSevices.class));
                } else {
                    changeWallPagerSwitch(R.mipmap.ic_switch_on, R.mipmap.ic_two_layer, 0, UIUtils.dip2px(44, this));
                    startService(new Intent(this, ListenSevices.class));
                }
                mSwitchChangewallpager.setTag(!(Boolean) mSwitchChangewallpager.getTag());
                SettingConfig.WriteSettingBoolean(getBaseContext(), SettingConfig.CHANGE, (Boolean) mSwitchChangewallpager.getTag());
                break;
            case R.id.setting_wifichange_switch:
                mSwitchWifichange.setImageResource((Boolean) mSwitchWifichange.getTag() ? R.mipmap.ic_switch_off : R.mipmap.ic_switch_on);
                mSwitchWifichange.setTag(!(Boolean) mSwitchWifichange.getTag());
                SettingConfig.WriteSettingBoolean(getBaseContext(), SettingConfig.WIFI, (Boolean) mSwitchWifichange.getTag());
                break;
            case R.id.setting_boytype_view:
                mBoyTypeCheckView.setVisibility(View.VISIBLE);
                mGirlTypeCheckView.setVisibility(View.INVISIBLE);
                SettingConfig.WriteSettingString(getBaseContext(), SettingConfig.SEX, SettingConfig.BOY);
                break;
            case R.id.setting_girltype_view:
                mBoyTypeCheckView.setVisibility(View.INVISIBLE);
                mGirlTypeCheckView.setVisibility(View.VISIBLE);
                SettingConfig.WriteSettingString(getBaseContext(), SettingConfig.SEX, SettingConfig.GIRL);
                break;
            case R.id.setting_clearcache_view:
                doPop();
                break;
            case R.id.setting_about_bcy_view:
                Intent intent = new Intent(this, DownLoadActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
        }
    }

    private void changeWallPagerSwitch(int ic_switch_on, int layer_resource_id, int start_height, int end_height) {
        mSwitchChangewallpager.setImageResource(ic_switch_on);
        mContainerChangeWallpager.setBackgroundResource(layer_resource_id);
        ValueAnimator heightAnimator = ValueAnimator.ofInt(start_height, end_height);
        heightAnimator.addUpdateListener(getUpdateHeightAnimatorListener());
        heightAnimator.start();
    }

    @NonNull
    private ValueAnimator.AnimatorUpdateListener getUpdateHeightAnimatorListener() {
        return new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int val = (int) valueAnimator.getAnimatedValue();
                ViewGroup.LayoutParams layoutParams = mContainerWifichange.getLayoutParams();
                layoutParams.height = val;
                mContainerWifichange.setLayoutParams(layoutParams);

                ViewGroup.LayoutParams changeWallPagerParams = mContainerChangeWallpager.getLayoutParams();
                changeWallPagerParams.height = UIUtils.dip2px(44, SettingActivity.this) + val;
                mContainerChangeWallpager.setLayoutParams(changeWallPagerParams);
            }
        };
    }

    private void renderCacheSize() {
        new AsyncTask<Void, String, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return getCacheSize();
            }

            @Override
            protected void onPostExecute(String s) {
                mCacheSizeTv.setText(s);
            }
        }.execute();
    }

    private void clearCache() {
        if (!mClearFlag) {
            Snackbar snackbar = Snackbar.make(mSnack, getString(R.string.clear_yes_no), Snackbar.LENGTH_LONG);
            View view = snackbar.getView();
            TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
            tv.setTextColor(Color.WHITE);
            snackbar.setAction(getString(R.string.yes), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Observable.create(new Observable.OnSubscribe<String>() {
                        @Override
                        public void call(Subscriber<? super String> subscriber) {
                            mClearFlag = true;
                            Glide.get(getBaseContext()).clearDiskCache();
                            subscriber.onNext(getCacheSize());
                        }
                    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                            subscribe(new Action1<String>() {
                                @Override
                                public void call(String s) {
                                    Glide.get(getBaseContext()).clearMemory();
                                    mCacheSizeTv.setText(s);
                                    mClearFlag = false;
                                }
                            });
                }
            }).show();
        }

    }

    private String getCacheSize() {
        File imageDirectory = Glide.getPhotoCacheDir(getBaseContext(), "bcyWall_cache");
        long imageDirectoryLength = 0;
        if (imageDirectory.exists()) {
            imageDirectoryLength = CacheUtils.getFilesSize(imageDirectory);
        }
        long length = imageDirectoryLength;
        String size = CacheUtils.getFormatSize(length);
        return size;
    }

    private void doPop() {
        clearCache();
    }

    private void close() {
        if (!SettingConfig.ReadSettingString(getBaseContext(), SettingConfig.SEX).equals(temp_sex)) {
            setResult(SETTING_CHANGE);
        } else {
            setResult(SETTING_NOT_CHANGE);
        }
        finish();
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    public void onBackPressed() {
        close();
    }

}
